package org.lejos.example;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import lejos.nxt.*;
/**
 *
 * @author alex
 */
public class StopAfterHitting {
    private TouchSensor touchSensor;
    private boolean done;
    public static void main(String[] args)
    {
        final StopAfterHitting robot;
        robot = new StopAfterHitting();
        robot.run();
    }
    public StopAfterHitting()
    {
        final SensorPort touchPort;
        touchPort = SensorPort.S2;
        touchSensor = new TouchSensor(touchPort);
        touchPort.addSensorPortListener(new TouchListener());

    }
    public void run(){
        int distance;
        Motor.B.setSpeed(360);
        Motor.C.setSpeed(360);
        moveBackward();
        waitForExit();
    }
    private void waitForExit()
    {
        while(!(done))
        {
            try
            {
                synchronized(this)
                {
                    wait(0);
                }

            }
            catch(final InterruptedException ex)
            {

            }
        }
    }
    private void moveBackward()
    {
        Motor.B.backward();
        Motor.C.backward();
    }
    private void exit()
    {
        synchronized(this)
        {
            done=true;
            notifyAll();
        }
    }
    private class TouchListener
            implements SensorPortListener
    {
        public void stateChanged(final SensorPort port,final int oldValue, final int newValue)
        {
            if(touchSensor.isPressed())
            {
                exit();
            }
        }
    }
}
